package net.lookyou.boot.demo.config.security.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import net.lookyou.boot.demo.entity.SysRole;
import net.lookyou.boot.demo.entity.SysUser;
import net.lookyou.boot.demo.entity.SysUserRole;
import net.lookyou.boot.demo.mapper.RoleMapper;
import net.lookyou.boot.demo.mapper.UserMapper;
import net.lookyou.boot.demo.mapper.UserRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 手机短信登录，UserDetailsService
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
public class BaseUserDetailsService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;


    public Collection<GrantedAuthority> authorities(SysUser user){
        if(Objects.isNull(user)){
            return null;
        }

        // 添加权限
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        List<SysUserRole> sysUserRoleList = userRoleMapper.selectList(
                new EntityWrapper<SysUserRole>()
                        .eq("user_id", user.getId())
        );
        for (SysUserRole userRole : sysUserRoleList) {
            SysRole role = roleMapper.selectById(userRole.getRole_Id());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }
}
